package com.cg.asm.core.controller.auth;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cg.asm.core.util.AsmApiUtils;
import com.cg.asm.core.util.AsmCommonUtil;
import com.cg.asm.client.CommonUtil;
import com.cg.asm.client.HttpClientUtils;
import com.cg.asm.client.constans.ConstantsEnum;
import com.cg.asm.client.domain.http.HttpClientResult;
import com.cg.asm.client.domain.user.UserInfo;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/auth/session")
public class SessionController {

    /**
     * 获取Session中的用户信息
     *
     * @return
     */
    @PostMapping("/sessionUserInfo")
    @ResponseBody
    public JSONObject getSessionUserInfo(HttpServletRequest request) {
        String token = request.getParameter("token");
        String authId = request.getParameter("authId");
        String requestUrl = request.getParameter("requestUrl");
        String host = request.getHeader("host");
        String contextPath = request.getContextPath();
        if (StringUtil.isNotEmpty(token) || StringUtil.isNotEmpty(authId) || StringUtil.isNotEmpty(requestUrl) || StringUtil.isNotEmpty(host)) {
            boolean resultValue;
            String returnCode;
            String returnMsg;
            UserInfo userInfo = null;
            String sid = AsmApiUtils.tokenDecrypt(token);
            Map<String, String> headers = new HashMap<>();
            headers.put("Cookie", "JSESSIONID=" + sid);
            Map<String, String> param = new HashMap<>();
            param.put("authId", authId);
            param.put("requestUrl", requestUrl);
            try {
                String hostUrl = "http://" + host + contextPath + "/login/sessionUserInfoByAsm";
                HttpClientResult httpClientResult = HttpClientUtils.doGet(hostUrl, headers, param);
                JSONObject data = JSONObject.parseObject(httpClientResult.getContent());
                if (httpClientResult.getCode() == 200) {
                    if ("error".equals(data.get("returnType"))) {
                        resultValue = false;
                    } else {
                        userInfo = JSON.parseObject(JSON.toJSONString(data.get("returnData")), UserInfo.class);
                        resultValue = true;
                    }
                } else {
                    resultValue = false;
                }
                returnCode = (String) data.get("returnCode");
                returnMsg = (String) data.get("returnMsg");
            } catch (Exception e) {
                returnCode = "";
                if (e.getMessage().indexOf("timeout") > -1) {
                    returnMsg = "响应请求,网络超时!";
                } else if (e.getMessage().indexOf("Connection refused: connect") > -1) {
                    returnMsg = "连接失败:与总控系统失去联系!";
                } else {
                    returnMsg = e.getMessage();
                }
                resultValue = false;
            }
            if (resultValue == false) {
                return CommonUtil.errorJsonAndSid(returnCode, returnMsg, sid);
            } else {
                return CommonUtil.successJsonAndSid(userInfo, sid);
            }
        } else {
            String returnCode = ConstantsEnum.RESPONSE_E_AAAB.getKey();
            String returnMsg = ConstantsEnum.RESPONSE_E_AAAB.getValue();
            return CommonUtil.errorJson(returnCode, returnMsg);
        }
    }

    /**
     * 实现单点登录
     *
     * @return
     */
    @PostMapping("/singleLogin")
    @ResponseBody
    public JSONObject singleLogin(HttpServletRequest request, HttpServletResponse httpServletResponse) {
        String username = request.getParameter("username");
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String platformTypeCode = request.getParameter("platformTypeCode");
        String host = request.getHeader("host");
        String contextPath = request.getContextPath();
        if (StringUtil.isNotEmpty(username) && StringUtil.isNotEmpty(platformTypeCode)) {
            HttpSession session = request.getSession(false);
            JSONObject asmLogin = session == null ? null : (JSONObject) session.getAttribute(AsmCommonUtil.ASMCONTEXELOGINKEY);
            if (null != asmLogin) {
                return asmLogin;
            } else {
                String returnMsg;
                String randomPwd = RandomStringUtils.randomAlphanumeric(10);
                Map<String, String> headers = new HashMap<>();
                Map<String, String> param = new HashMap<>();
                param.put("username", username);
                param.put("password", randomPwd);
                param.put("encodingPwd", bCryptPasswordEncoder.encode(randomPwd));
                param.put("singleLogin", "true");
                param.put("platformTypeCode", platformTypeCode);
                try {
                    String hostUrl = "http://" + host + contextPath + "/login";
                    HttpClientResult httpClientResult = HttpClientUtils.doPost(hostUrl, headers, param);
                    JSONObject data = JSONObject.parseObject(httpClientResult.getContent());
                    if (httpClientResult.getCode() == 200) {
                        Map<String, Object> returnData = (Map<String, Object>) data.get("returnData");
                        if (null != returnData) {
                            String serviceSid = (String) returnData.get("tokenValue");
                            if (StringUtil.isNotEmpty(serviceSid)) {
                                httpServletResponse.addHeader("set-cookie", "JSESSIONID=" + AsmApiUtils.tokenDecrypt(serviceSid) + "; Path=/; HttpOnly");
                            }
                        }
                    }
                    return data;
                } catch (Exception e) {
                    if (e.getMessage().indexOf("timeout") > -1) {
                        returnMsg = "响应请求,网络超时!";
                    } else if (e.getMessage().indexOf("Connection refused: connect") > -1) {
                        returnMsg = "连接失败:与总控系统失去联系!";
                    } else {
                        returnMsg = e.getMessage();
                    }
                    return CommonUtil.errorJson("", returnMsg);
                }
            }
        } else {
            String returnCode = ConstantsEnum.RESPONSE_E_AAAB.getKey();
            String returnMsg = ConstantsEnum.RESPONSE_E_AAAB.getValue();
            return CommonUtil.errorJson(returnCode, returnMsg);
        }
    }

    /**
     * 密码加密
     *
     * @return
     */
    @GetMapping("/pwdEnCoder")
    @ResponseBody
    public JSONObject pwdEnCoder(HttpServletRequest request) {
        String password = request.getParameter("password");
        if (StringUtil.isNotEmpty(password)) {
            return CommonUtil.successJson(new BCryptPasswordEncoder().encode(password));
        } else {
            return CommonUtil.errorJson("加密失败：空密码无法加密");
        }
    }
}
